package com.example.active.trans;

import com.example.active.utils.GsonUtils;
import com.example.active.utils.HttpUtil;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.util.HashMap;
import java.util.Map;

public class Receiver implements Runnable {
    public String url;
    public String topicName;
    public String accessToken;

    public Receiver(String url, String topicName, String accessToken) {
        this.url = url;
        this.topicName = topicName;
        this.accessToken = accessToken;
    }

    @Override
    public void run() {
        ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
        try {
            Connection connection = connectionFactory.createConnection();
            connection.start();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Topic topic = session.createTopic(topicName);
            MessageConsumer messageConsumer = session.createConsumer(topic);
            messageConsumer.setMessageListener(new MyMessageListener(accessToken));
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }
}

class MyMessageListener implements MessageListener {
    private final String accessToken;
    private final String requestUrl = "https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1";
    private Map<String, Object> map;

    public MyMessageListener(String accessToken) {
        this.accessToken = accessToken;
        this.map = new HashMap<>();
        // 由自动检测语言翻译为中文
        map.put("from", "auto");
        map.put("to", "zh");
    }

    @Override
    public void onMessage(Message message) {
        TextMessage textMessage = (TextMessage) message;
        try {
            String[] tmp = textMessage.getText().split(" : ");
            String user = tmp[0], msg = tmp[1];
            map.put("q", msg);
            String result = HttpUtil.post(requestUrl, accessToken, GsonUtils.toJson(map));
            JsonObject jsonObject = JsonParser.parseString(result).getAsJsonObject();
            jsonObject = jsonObject.get("result").getAsJsonObject();
            jsonObject = jsonObject.get("trans_result").getAsJsonArray().get(0).getAsJsonObject();
            msg = jsonObject.get("dst").getAsString();
//            System.err.println(result);
            System.out.println(String.join(" : ", user, msg));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

